package butines.game;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import java.util.TreeSet;


public class Messenger {

	private Set<Message> queued = new TreeSet<Message>();
	private LinkedList<Message> buffer = new LinkedList<Message>();

	private float frameTime;

	public Messenger() {

	}

	public void dispatch(Enum<?> type, GameObject sender, GameObject receiver, float delay, Object... args) {
		if (delay < 0) {
			delay = 0;
		}
		if (args == null) {
			args = new Object[0];
		}
		float dispatchTime = frameTime + delay;
		Message message = new Message(type, sender, receiver, dispatchTime, args);
		buffer.addLast(message);
	}

	private void discharge(Message message) {
		GameObject receiver = message.getReceiver();
		receiver.handleMessage(message);
	}

	public void dispatchMessages(float frameTime) {
		this.frameTime = frameTime;
		
		while (buffer.isEmpty() == false) {
			Message message = buffer.removeFirst();
			if (message.getDispatchTime() <= frameTime) {
				discharge(message);
			} else {
				queued.add(message);
			}
		}

		Iterator<Message> i = queued.iterator();
		while (i.hasNext()) {
			Message message = i.next();
			if (message.getDispatchTime() >= frameTime) {
				discharge(message);
				i.remove();
			}
		}

	}

}
